package preorder

import (
    "time"
	"strconv"
	"dhfshop/controllers/base"
	"dhfshop/models/preorder"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"dhfshop/service/timer"
	preorderlayer "dhfshop/domain/preorder"
)

type ResItemController struct {
	base.BaseController
}

func (this *ResItemController) List() {
	curRoleId := this.Ctx.Input.GetData("curRoleId").(int)
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if curRoleId == 2 {
	    query["partner_id"] = strconv.FormatInt(partnerId, 10)
	}
	var allowStoreId []int64
	if this.CurrentUser != nil {
	    allowStoreId = this.CurrentUser.AllowStoreId
	}
	//beego.Debug("allowStoreId:", allowStoreId)
	l, cnt, err := preorder.GetAllResItems(allowStoreId,query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount int64               `json:"total_count"`
		ResItem    []*preorder.ResItem `json:"res_item"`
	}{TotalCount: cnt, ResItem: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *ResItemController) Post() {
	var v preorder.ResItem
	this.ParseForm(&v)
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if resType, err := preorder.GetResTypeById(v.ResTypeId); err != nil {
		this.ServeError(err.Error())
		return
	} else {
		v.ResType = resType
	}
	id, err := preorder.AddResItem(&v)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	v.ResItemId = int64(id)
	rsp := struct {
		ResItemId  int64     `json:"res_item_id"`
		Modified time.Time `json:"modified"`
	}{ResItemId: id, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ResItemController) Update() {
	var v preorder.ResItem
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ResItemId, "res_item_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	if v.ResTypeId > 0 {
	    if resType, err := preorder.GetResTypeById(v.ResTypeId); err != nil {
			this.ServeError(err.Error())
			return
		} else {
			v.ResType = resType
		}
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"res_item_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := preorder.UpdateResItemById(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		ResItemId  int64     `json:"res_item_id"`
		Modified time.Time `json:"modified"`
	}{ResItemId: v.ResItemId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ResItemController) AutoProducePut() {
	v := struct {
		PartnerId   int64  `form:"-"`
		ResItemId   int64  `form:"res_item_id" valid:"Required"`
		AutoProduce int    `form:"auto_produce"`
		ProduceTime string `form:"produce_time"`
		TaskId      int64  `form:"-"`
	}{TaskId: 0}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ResItemId, "res_item_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	if v.AutoProduce == 1 {
	    if _, err := time.Parse(consts.TIME_FORMAT, v.ProduceTime); err != nil {
			this.ServeError(err.Error())
			return
	    }
	    if id := timer.AddTimerTask(1,v.ProduceTime,v.ResItemId,preorderlayer.OnOnceDayTick); id > 0 {
		   v.TaskId = int64(id)
		}
	}else{
	    timer.DelTimerTask(int(v.ResItemId)) 
	}
	m := &preorder.ResItem{ResItemId:v.ResItemId,AutoProduce:v.AutoProduce,ProduceTime:v.ProduceTime,TaskId:v.TaskId}
	err := preorder.UpdateResItemById(m, "auto_produce", "produce_time", "task_id")
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		ResItemId  int64     `json:"res_item_id"`
		Modified time.Time `json:"modified"`
	}{ResItemId: v.ResItemId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ResItemController) Delete() {
	var v preorder.ResItem
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ResItemId, "res_item_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	err := preorder.DeleteResItem(v.ResItemId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		ResItemId  int64     `json:"res_item_id"`
		Modified time.Time `json:"modified"`
	}{ResItemId: v.ResItemId, Modified: time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}

